package com.hassean.we.admin.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.hassean.we.admin.common.constant.CommonConstant;
import com.hassean.we.admin.common.util.Query;
import com.hassean.we.admin.common.util.R;
import com.hassean.we.admin.common.web.BaseController;
import com.hassean.we.admin.model.entity.TbRescueTeam;
import com.hassean.we.admin.model.entity.TbSimInfo;
import com.hassean.we.admin.model.entity.TbTerminal;
import com.hassean.we.admin.model.entity.TbTerminalLocation;
import com.hassean.we.admin.service.TbRescueTeamService;
import com.hassean.we.admin.service.TbSimInfoService;
import com.hassean.we.admin.service.TbTerminalLocationService;
import com.hassean.we.admin.service.TbTerminalService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yajun
 * @since 2019-03-29
 */
@Api(description = "终端接口")
@RestController
@RequestMapping("/tbTerminal")
public class TbTerminalController extends BaseController {
    @Autowired private TbTerminalService tbTerminalService;
    @Autowired private TbRescueTeamService tbRescueTeamService;
    @Autowired private TbSimInfoService tbSimInfoService;
    @Autowired private TbTerminalLocationService tbTerminalLocationService;
    /**
    * 通过ID查询
    *
    * @param id ID
    * @return TbTerminal
    */
    @ApiOperation(value = "通过ID查询终端" ,  notes="通过ID查询终端")
    @GetMapping("/{id}")
    public R<TbTerminal> get(@PathVariable Long id) {
        return new R<>(tbTerminalService.selectById(id));
    }


    /**
    * 分页查询信息
    *
    * @param params 分页对象
    * @return 分页对象
    */
    @ApiOperation(value = "分页查询终端" ,  notes="分页查询终端")
    @RequestMapping("/page")
    public R<Map<String, Object>> getTbTerminalPage(@RequestParam Map<String, Object> params) {
        EntityWrapper entity = new EntityWrapper<>();
        params.put(CommonConstant.DEL_FLAG, CommonConstant.STATUS_NORMAL);
        List< Map<String, Object>>resultList = new ArrayList<>();
        Map<String,Object> resultMap = new HashMap<>();
        //类型，在线状态，部门

        EntityWrapper er=new EntityWrapper<>();
        if (params.get("state")!=null&&!(params.get("state")).equals("")){
            Integer state = Integer.parseInt(params.get("state").toString());
            params.put("state",state);//在线状态条件查询
        }
        if (params.get("type")!=null&&!(params.get("type")).equals("")){
            System.out.println("params.get(type):"+params.get("type").getClass());
            Integer type = Integer.parseInt(params.get("type").toString());
            params.put("type",type);//类型条件查询
        }
        Long departmentId = null;
        if (params.get("departmentId")!=null&&!(params.get("departmentId")).equals("")){
            departmentId = Long.parseLong(params.get("departmentId").toString());
            params.remove("departmentId");

        }
        /**
         * 如果省级用户id为10，11是A市id，12是B市id，13是A市C区id,10可以查10，11，12，13下属的所有终端机，
         * 11可以查11，13下属的所有终端机
         * 还没写完？
         */


        if (params.get("phone")!=null&&!(params.get("phone")).equals("")){
            String phone = params.get("phone").toString();//被叫电话号码
            params.remove("phone");
            //通过电话号码获取终端id
            List<Map<String, Object>> list = tbTerminalService.selectTerminalIdByPhone(phone);
            //获取被叫终端id
            if(!list.isEmpty()){

                params.put("terminal_id",list.get(0).get("terminal_id"));
            }

        }


        if (params.get("page")!=null&&!(params.get("page")).equals("")){
            Integer page = Integer.parseInt(params.get("page").toString());
            params.put("page",page);
        }else{
            Integer page = 1;
            params.put("page",page);
        }

        if (params.get("limit")!=null&&!(params.get("limit")).equals("")){
            Integer limit = Integer.parseInt(params.get("limit").toString());
            params.put("limit",limit);
        }else{
            Integer limit = 10;
            params.put("limit",limit);
        }

        entity.orderDesc(Arrays.asList(new String [] {"terminal_id"}));//降序
        Page<TbTerminal> page = tbTerminalService.selectPage(new Query<>(params), entity);

        for (int i = 0; i <page.getRecords().size() ; i++) {
            Map<String,Object>map = new HashMap<>();
            map.put("terminalId",page.getRecords().get(i).getTerminalId());
            map.put("terminalNumber",page.getRecords().get(i).getTerminalNumber());
            map.put("ownerName",page.getRecords().get(i).getOwnerName());
            map.put("type",page.getRecords().get(i).getType());
            map.put("state",page.getRecords().get(i).getState());

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String addTime = sdf.format(page.getRecords().get(i).getAddTime());
            map.put("addTime",addTime);
            map.put("numberAttribution",page.getRecords().get(i).getNumberAttribution());
            map.put("imsiCode",page.getRecords().get(i).getImsiCode());
            map.put("imeiCode",page.getRecords().get(i).getImeiCode());
            map.put("temp",page.getRecords().get(i).getTemp());
            map.put("status",page.getRecords().get(i).getStatus());
            map.put("remark",page.getRecords().get(i).getRemark());//救援单位名称
            map.put("advanceText",page.getRecords().get(i).getAdvanceText());
            map.put("advanceDate",page.getRecords().get(i).getAdvanceDate());
            map.put("delFlag",page.getRecords().get(i).getDelFlag());
            map.put("registerDate",page.getRecords().get(i).getRegisterDate());
            Long rescueTeamId =page.getRecords().get(i).getRescueTeamId();//获取所属单位id
           Long  simInfoId =  page.getRecords().get(i).getSimInfoId();//获取sim卡id
           if(rescueTeamId!=null){
               TbRescueTeam tbRescueTeam =  tbRescueTeamService.selectById(rescueTeamId);
               if(tbRescueTeam!=null){
                   //如果时所属单位条件查询
                   if(departmentId!=null){
                       if(tbRescueTeam.getDepartmentId()==departmentId){
                           map.put("tbRescueTeam",tbRescueTeam);
                       }else{
                           continue;
                       }
                   }else{
                       map.put("tbRescueTeam",tbRescueTeam);
                   }


               }
           }
           if(simInfoId!=null){
               TbSimInfo tbSimInfo = tbSimInfoService.selectById(simInfoId);
               if(tbSimInfo!=null){
                   map.put("tbSimInfo",tbSimInfo);
               }
           }

            resultList.add(map);
        }
        resultMap.put("total",page.getTotal());//总条数
        resultMap.put("size",page.getSize());//每一页多少条
        resultMap.put("pages",page.getPages());//总页数
        resultMap.put("curren",page.getCurrent());//起始页
        resultMap.put("resultList",resultList);

        return new R<>(resultMap);

    }





    @RequestMapping("/tbTerminalList")
    public R<Map<String, Object>> tbTerminalList() {
        EntityWrapper entity = new EntityWrapper<>();
        entity.eq(CommonConstant.DEL_FLAG, CommonConstant.STATUS_NORMAL);

        List< Map<String, Object>>resultList = new ArrayList<>();
        Map<String,Object> resultMap = new HashMap<>();
        //类型，在线状态，部门
         entity.orderDesc(Arrays.asList(new String [] {"terminal_id"}));//降序
         List<TbTerminal>tbTerminalList =   tbTerminalService.selectList(entity);
        for (int i = 0; i <tbTerminalList.size() ; i++) {
            Map<String,Object>map = new HashMap<>();
            map.put("terminalId",tbTerminalList.get(i).getTerminalId());


            Long   terminal_id = tbTerminalList.get(i).getTerminalId();
            EntityWrapper entity_terminal_id = new EntityWrapper<>();
            entity_terminal_id.eq("terminal_id",terminal_id);
            map.put("longitude","");
            map.put("latitude","");
            TbTerminalLocation tbTerminalLocation =   tbTerminalLocationService.selectOne(entity_terminal_id);
            if(tbTerminalLocation!=null){
                ;
                map.put("longitude",tbTerminalLocation.getLongitude());
                map.put("latitude",tbTerminalLocation.getLatitude());

            }

            map.put("terminalNumber",tbTerminalList.get(i).getTerminalNumber());
            map.put("ownerName",tbTerminalList.get(i).getOwnerName());
            map.put("type",tbTerminalList.get(i).getType());
            map.put("state",tbTerminalList.get(i).getState());

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String addTime = sdf.format(tbTerminalList.get(i).getAddTime());
            map.put("addTime",addTime);
            map.put("numberAttribution",tbTerminalList.get(i).getNumberAttribution());
            map.put("imsiCode",tbTerminalList.get(i).getImsiCode());
            map.put("imeiCode",tbTerminalList.get(i).getImeiCode());
            map.put("temp",tbTerminalList.get(i).getTemp());
            map.put("status",tbTerminalList.get(i).getStatus());
            map.put("remark",tbTerminalList.get(i).getRemark());//救援单位名称
            map.put("advanceText",tbTerminalList.get(i).getAdvanceText());
            map.put("advanceDate",tbTerminalList.get(i).getAdvanceDate());
            map.put("delFlag",tbTerminalList.get(i).getDelFlag());
            map.put("registerDate",tbTerminalList.get(i).getRegisterDate());
            Long rescueTeamId =tbTerminalList.get(i).getRescueTeamId();//获取所属单位id
            Long  simInfoId =  tbTerminalList.get(i).getSimInfoId();//获取sim卡id
            if(rescueTeamId!=null){
                TbRescueTeam tbRescueTeam =  tbRescueTeamService.selectById(rescueTeamId);
                if(tbRescueTeam!=null){
                        map.put("tbRescueTeam",tbRescueTeam);
                }
            }
            if(simInfoId!=null){
                TbSimInfo tbSimInfo = tbSimInfoService.selectById(simInfoId);
                if(tbSimInfo!=null){
                    map.put("tbSimInfo",tbSimInfo);
                }
            }

            resultList.add(map);
        }
        resultMap.put("resultList",resultList);

        return new R<>(resultMap);

    }

    /**
     * 添加
     * @param terminalNumber
     * @param simNumber
     * @param ownerName
     * @param departmentName
     * @param simOwnerName
     * @param departmentId
     * @param type
     * @param state
     * @param numberAttribution
     * @param ImsiCode
     * @param ImeiCode
     * @param provinces
     * @param municipalities
     * @param districts
     * @param townStreet
     * @return success/false
     */



//    public Integer add2( @RequestParam  String terminalNumber,@RequestParam String simNumber,@RequestParam String ownerName,
//                             @RequestParam String departmentName,@RequestParam String simOwnerName,
//                             @RequestParam  Long departmentId,@RequestParam Integer type,@RequestParam Integer state,@RequestParam String numberAttribution,
//                             @RequestParam  String ImsiCode,@RequestParam  String ImeiCode,@RequestParam String provinces,@RequestParam String municipalities,
//                             @RequestParam  String districts,@RequestParam  String townStreet) {
//        Boolean flag = false;
//        TbTerminal tbTerminal = new TbTerminal();
//        TbSimInfo tbSimInfo = new TbSimInfo();
//        tbSimInfo.setOwnerName(simOwnerName);//实名登记的人
//        tbSimInfo.setSimNumber(simNumber);
//        tbSimInfo.setDepartmentName(departmentName);//所属单位
//        Long id = tbSimInfoService.insertAndReturnId(tbSimInfo);
//        if(id==0L){
//            return CommonConstant.phoneRepetition;//2000电话号码重复
//        }
//        Long rescueTeamId = null;
//        if(id!=0L){
//            TbRescueTeam tbRescueTeam = new TbRescueTeam();
//            tbRescueTeam.setDepartmentName(departmentName);
//            tbRescueTeam.setDistricts(districts);
//            tbRescueTeam.setTownStreet(townStreet);
//            tbRescueTeam.setProvinces(provinces);
//            tbRescueTeam.setMunicipalities(municipalities);
//            tbRescueTeam.setDepartmentId(departmentId);
//            tbRescueTeamService.insertAndReturnId(tbRescueTeam);
//            rescueTeamId =  tbRescueTeam.getRescueTeamId();
//        }
//        if(rescueTeamId!=null){
//            tbTerminal.setSimInfoId(id);
//            tbTerminal.setTerminalNumber(terminalNumber);
//            //判重
//            EntityWrapper entityWrapper =   new EntityWrapper<>();
//            entityWrapper.eq("terminal_number",terminalNumber);
//            TbTerminal terminal   = tbTerminalService.selectOne(entityWrapper);
//            if(terminal!=null){
//                return CommonConstant.tbTerminalRepetition;//2001终端号码重复
//            }else {
//                tbTerminal.setImeiCode(ImeiCode);
//                tbTerminal.setImsiCode(ImsiCode);
//                tbTerminal.setState(state);
//                tbTerminal.setType(type);
//                tbTerminal.setRescueTeamId(rescueTeamId);//有问题
//                tbTerminal.setNumberAttribution(numberAttribution);
//                tbTerminal.setOwnerName(ownerName);//终端机负责人
//                tbTerminalService.insert(tbTerminal);
//                return CommonConstant.success;//1000成功
//            }
//
//            }else {
//            return CommonConstant.failed ;// 2002失败;
//        }
//    }


    @ApiOperation(value = "添加终端" ,  notes="添加终端")
    @PostMapping("/add")
    public Integer add( @RequestParam  String terminalNumber,@RequestParam String simNumber,@RequestParam String ownerName,
                        @RequestParam String departmentName,@RequestParam String simOwnerName,
                        @RequestParam  Long departmentId,@RequestParam Integer type,@RequestParam Integer state,@RequestParam String numberAttribution,
                        @RequestParam  String ImsiCode,@RequestParam  String ImeiCode,@RequestParam String provinces,@RequestParam String municipalities,
                        @RequestParam  String districts,@RequestParam  String townStreet) {
        Integer code =   tbTerminalService.saveTbTerminal( terminalNumber,  simNumber, ownerName,departmentName,   simOwnerName, departmentId,  type,  state, numberAttribution, ImsiCode,   ImeiCode,   provinces,   municipalities, districts,   townStreet);

        return code;

    }



    /**
     * 删除
     * @param id ID
     * @return success/false
     */
    @ApiOperation(value = "删除终端" ,  notes="删除终端")
    @DeleteMapping("/{id}")
    public R<Boolean> delete(@PathVariable Long id) {
        TbTerminal tbTerminal = new TbTerminal();
        tbTerminal.setTerminalId(id);
        tbTerminal.setUpdateTime(new Date());
        tbTerminal.setDelFlag(CommonConstant.STATUS_DEL);
        return new R<>(tbTerminalService.updateById(tbTerminal));
    }


    /**
     *  编辑
     * @param terminalNumber
     * @param simNumber
     * @param ownerName
     * @param departmentName
     * @param simOwnerName
     * @param terminalId
     * @param rescueTeamId
     * @param type
     * @param state
     * @param numberAttribution
     * @param ImsiCode
     * @param ImeiCode
     * @param simInfoId
     * @return
     */
    @ApiOperation(value = "编辑终端" ,  notes="编辑终端")
    @PutMapping
    public R<Boolean> edit( @RequestParam  String terminalNumber,@RequestParam String simNumber,@RequestParam String ownerName,
                            @RequestParam String departmentName,@RequestParam String simOwnerName,@RequestParam Long terminalId,
                            @RequestParam  Long rescueTeamId,@RequestParam Integer type,@RequestParam Integer state,@RequestParam String numberAttribution,
                            @RequestParam  String ImsiCode,@RequestParam  String ImeiCode,@RequestParam Long simInfoId,@RequestParam  String provinces,
                            @RequestParam  String municipalities,@RequestParam  String districts,@RequestParam  String townStreet ) {
        TbSimInfo tbSimInfo =   tbSimInfoService.selectById(simInfoId);
        Boolean flag = true;
        if(simOwnerName!=null&&!simOwnerName.equals("")){
            tbSimInfo.setOwnerName(simOwnerName);//实名登记的人
        }
        if(simNumber!=null&&!simNumber.equals("")){
            tbSimInfo.setSimNumber(simNumber);
        }
            tbSimInfo.setDepartmentName(departmentName);//所属单位

        tbSimInfo.setUpdateTime(new Date());
        flag = tbSimInfoService.updateById(tbSimInfo);
        if(flag){
            TbRescueTeam tbRescueTeam =  tbRescueTeamService.selectById(rescueTeamId);
            if(departmentName!=null&&!departmentName.equals("")){
                tbRescueTeam.setDepartmentName(departmentName);
            }
                tbRescueTeam.setDistricts(districts);
                tbRescueTeam.setTownStreet(townStreet);
                tbRescueTeam.setProvinces(provinces);
                tbRescueTeam.setMunicipalities(municipalities);


            flag= tbRescueTeamService.updateById(tbRescueTeam);
        }
        if(flag){
            TbTerminal tbTerminal = tbTerminalService.selectById(terminalId);
            if(terminalNumber!=null&&terminalNumber.equals("")){
                tbTerminal.setTerminalNumber(terminalNumber);
            }
                tbTerminal.setImeiCode(ImeiCode);
                tbTerminal.setImsiCode(ImsiCode);
                tbTerminal.setState(state);
                tbTerminal.setType(type);
                tbTerminal.setRemark(departmentName);
                tbTerminal.setNumberAttribution(numberAttribution);
                tbTerminal.setOwnerName(ownerName);//终端机负责人

            tbTerminal.setUpdateTime(new Date());
            flag=tbTerminalService.updateById(tbTerminal);
        }
            return new R<>(flag);


    }
    //获取某救援单位下的所有终端
    @ApiOperation(value = "获取某救援单位下的所有终端" ,  notes="获取某救援单位下的所有终端")
    @RequestMapping("/tbTerminalListGroupByRescueTeamId")
    //这个方法很重要，但是要怎么修改？
    public R<List> tbTerminalByRescueTeamId(@RequestParam  String rescueTeamId){
        EntityWrapper entity = new EntityWrapper<>();
        entity.eq("rescue_team_id",rescueTeamId);
        List<Object>selectList = tbTerminalService.selectList(entity);
        return  new R<>(selectList);
    }
}
